package template

import (
	"bytes"
	"io/ioutil"
	"os"
	"text/template"
)

// ExecuteTemplate 解析模板文件
func ExecuteTemplate(file string, data interface{}) (string, error) {
	if file == "" {
		return "", os.ErrNotExist
	}
	tmpl, err := template.ParseFiles(file)
	if err != nil {
		return "", err
	}
	var buf bytes.Buffer
	err = tmpl.Execute(&buf, data)
	return buf.String(), err
}

// ExecuteTemplateString 解析文本字符串
func ExecuteTemplateString(text string, data interface{}) (string, error) {
	if text == "" {
		return "", nil
	}
	tmpl, err := template.New("email").Parse(text)
	if err != nil {
		return "", err
	}
	var buf bytes.Buffer
	err = tmpl.Execute(&buf, data)
	return buf.String(), err
}

func ParseDingtalkMsg(path string) ([]byte, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	data, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}
	return data, nil
}
